package com.mutouren.modules.org.client;

import java.util.List;

import com.mutouren.common.entity.ResultCode;
import com.mutouren.common.entity.ResultInfo;
import com.mutouren.modules.org.client.config.ClientConfig;
import com.mutouren.modules.org.client.config.FunctionConfig;
import com.mutouren.modules.org.client.impl.OrgAuthenticationImpl;
import com.mutouren.modules.org.client.impl.OrgAuthorityImpl;
import com.mutouren.modules.org.client.proxy.OrgApiProxy;
import com.mutouren.modules.org.model.Function;

public class OrgManager {
	
	private volatile static boolean isInit = false;
	private volatile static OrgManager instance;
	
	private FunctionConfig functionConfig;
	private OrgAuthority orgAuthority;
	private OrgAuthentication orgAuthentication;
	
	private OrgManager() {
		this.functionConfig = FunctionConfig.getInstance();
		this.orgAuthentication = new OrgAuthenticationImpl();
		this.orgAuthority = new OrgAuthorityImpl();
	}
	
	@SuppressWarnings("unused")
	private static boolean checkInit() {
		ResultInfo<List<Function>> resultInfo = OrgApiProxy.getFunctionsOfApp(ClientConfig.getAppAlias());
		return resultInfo.getCode() == ResultCode.SUCCESS.value;
	}
	
	public synchronized static void init(String appAlias, String apiContextUrl) {
		if (isInit) {
			throw new RuntimeException("OrgManager already init");
		}
		
		ClientConfig.init(appAlias, apiContextUrl);
//		if (!checkInit()) {
//			throw new RuntimeException("OrgManager checkInit fail");
//		}
		isInit = true;
	}	
	
	public synchronized static OrgManager getInstance() {
		if (isInit == false) {
			throw new RuntimeException("please first init");
		}
		if (instance == null) {
			instance = new OrgManager();
		}
		return instance;
	}
	
	public OrgAuthority getAuthority(){
		return orgAuthority;
	}
	public OrgAuthentication getAuthentication() {
		return orgAuthentication;
	}
	
	public List<Function> getAllFunctionOfApp() {
		return functionConfig.getAllFunctionOfApp();
	}
	public int[] getFunctionIdsOfUser(int userId) {
		return functionConfig.getFunctionIdsOfUser(userId);
	}
}
